<template>
  <view class="my-favorites-page">
    <!-- 导航栏 -->
    <uni-nav-bar
      title="我的收藏"
      :border="false"
      background-color="#07C160"
      color="#FFFFFF"
      @clickLeft="goBack"
    />

    <!-- 收藏列表 -->
    <view class="favorites-list">
      <view
        v-for="item in favoritesList"
        :key="item.id"
        class="favorite-item"
        @click="goToDetail(item.id)"
      >
        <image class="goods-image" :src="item.images[0]" mode="aspectFill" />
        <view class="goods-info">
          <view class="goods-title">{{ item.title }}</view>
          <view class="goods-price">¥{{ item.price }}</view>
          <view class="goods-meta">
            <view class="seller-info">
              <image
                class="seller-avatar"
                :src="item.user.avatar"
                mode="aspectFill"
              />
              <text class="seller-name">{{ item.user.nickname }}</text>
            </view>
            <text class="favorite-time">{{
              formatTime(item.favoriteTime)
            }}</text>
          </view>
          <view class="goods-status">
            <uni-tag
              :text="getStatusText(item.status)"
              :type="getStatusType(item.status)"
              size="small"
            />
          </view>
        </view>
        <view class="favorite-actions">
          <button
            class="contact-btn"
            @click.stop="contactSeller(item)"
            v-if="item.status === 'active'"
          >
            联系
          </button>
          <button class="unfavorite-btn" @click.stop="removeFavorite(item)">
            取消收藏
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="favoritesList.length === 0 && !loading">
      <image
        class="empty-image"
        src="/static/images/empty-favorites.png"
        mode="aspectFit"
      />
      <text class="empty-text">暂无收藏的商品</text>
      <button class="browse-btn" @click="goToBrowse">去逛逛</button>
    </view>

    <!-- 加载状态 -->
    <uni-load-more
      :status="loadMoreStatus"
      :content-text="loadMoreText"
      v-if="favoritesList.length > 0"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  getUserFavorites,
  removeFavorite as removeFavoriteApi,
} from "../../api/user";
import { formatTime } from "../../utils/format";
import type { GoodsItem, GoodsStatus } from "../../types/goods";

// 收藏列表
const favoritesList = ref<(GoodsItem & { favoriteTime: string })[]>([]);

// 加载状态
const loading = ref(false);
const loadMoreStatus = ref("more");
const loadMoreText = reactive({
  contentdown: "上拉加载更多",
  contentrefresh: "加载中...",
  contentnomore: "没有更多了",
});

// 分页参数
const pageParams = reactive({
  page: 1,
  pageSize: 10,
});

// 页面加载时获取数据
onMounted(() => {
  loadFavoritesList();
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 加载收藏列表
const loadFavoritesList = async (loadMore = false) => {
  if (loading.value) return;

  loading.value = true;
  loadMoreStatus.value = "loading";

  try {
    // TODO: 调用API获取用户收藏列表
    // const response = await getUserFavorites(pageParams)
    // const newFavorites = response.data.list

    // 模拟数据
    const mockFavorites: (GoodsItem & { favoriteTime: string })[] = [
      {
        id: "1",
        title: "九成新MacBook Pro 16寸",
        description: "2023款，M2芯片，几乎全新",
        price: 15999,
        originalPrice: 18999,
        images: ["/static/images/goods3.jpg"],
        category: { id: "3", name: "数码", icon: "laptop" },
        status: "available" as GoodsStatus,
        viewCount: 256,
        favoriteCount: 32,
        createdAt: "2024-01-12T09:15:00Z",
        updatedAt: "2024-01-12T09:15:00Z",
        user: {
          id: "456",
          nickname: "李女士",
          avatar: "/static/images/avatar2.jpg",
          location: "上海市浦东新区",
        },
        favoriteTime: "2024-01-13T14:30:00Z",
      },
      {
        id: "2",
        title: "全新Nike Air Jordan 1",
        description: "正品保证，US9码",
        price: 899,
        originalPrice: 1299,
        images: ["/static/images/goods4.jpg"],
        category: { id: "1", name: "服装", icon: "shoe" },
        status: "sold" as GoodsStatus,
        viewCount: 89,
        favoriteCount: 12,
        createdAt: "2024-01-08T16:45:00Z",
        updatedAt: "2024-01-08T16:45:00Z",
        user: {
          id: "789",
          nickname: "王先生",
          avatar: "/static/images/avatar3.jpg",
          location: "广州市天河区",
        },
        favoriteTime: "2024-01-09T10:20:00Z",
      },
      {
        id: "3",
        title: "宜家北欧风书桌",
        description: "简约设计，使用半年",
        price: 299,
        originalPrice: 599,
        images: ["/static/images/goods5.jpg"],
        category: { id: "4", name: "家居", icon: "home" },
        status: "active" as GoodsStatus,
        viewCount: 45,
        favoriteCount: 6,
        createdAt: "2024-01-05T11:30:00Z",
        updatedAt: "2024-01-05T11:30:00Z",
        user: {
          id: "101",
          nickname: "陈小姐",
          avatar: "/static/images/avatar4.jpg",
          location: "深圳市南山区",
        },
        favoriteTime: "2024-01-06T08:15:00Z",
      },
    ];

    if (loadMore) {
      favoritesList.value.push(...mockFavorites);
    } else {
      favoritesList.value = mockFavorites;
    }

    // 更新加载状态
    if (mockFavorites.length < pageParams.pageSize) {
      loadMoreStatus.value = "noMore";
    } else {
      loadMoreStatus.value = "more";
      pageParams.page++;
    }
  } catch (error) {
    console.error("加载收藏列表失败:", error);
    uni.showToast({
      title: "加载失败",
      icon: "none",
    });
    loadMoreStatus.value = "more";
  } finally {
    loading.value = false;
  }
};

// 获取状态文本
const getStatusText = (status: GoodsStatus) => {
  const statusMap = {
    available: "在售",
    sold: "已售",
    reserved: "预定",
    offline: "已下架",
  };
  return statusMap[status] || "未知";
};

// 获取状态类型
const getStatusType = (status: GoodsStatus) => {
  const typeMap = {
    available: "success",
    sold: "warning",
    reserved: "primary",
    offline: "info",
  };
  return typeMap[status] || "default";
};

// 跳转到商品详情
const goToDetail = (goodsId: string) => {
  uni.navigateTo({
    url: `/pages/goods/detail?id=${goodsId}`,
  });
};

// 联系卖家
const contactSeller = (goods: GoodsItem & { favoriteTime: string }) => {
  uni.showActionSheet({
    itemList: ["微信联系", "电话联系", "站内消息"],
    success: (res: any) => {
      switch (res.tapIndex) {
        case 0:
          uni.showToast({
            title: "微信联系功能开发中",
            icon: "none",
          });
          break;
        case 1:
          uni.makePhoneCall({
            phoneNumber: "13800138000",
          });
          break;
        case 2:
          uni.showToast({
            title: "站内消息功能开发中",
            icon: "none",
          });
          break;
      }
    },
  });
};

// 取消收藏
const removeFavorite = (goods: GoodsItem & { favoriteTime: string }) => {
  uni.showModal({
    title: "取消收藏",
    content: `确定要取消收藏"${goods.title}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用取消收藏API
          // await removeFavoriteApi(goods.id)

          // 从列表中移除
          const index = favoritesList.value.findIndex(
            (item) => item.id === goods.id
          );
          if (index > -1) {
            favoritesList.value.splice(index, 1);
          }

          uni.showToast({
            title: "已取消收藏",
            icon: "success",
          });
        } catch (error) {
          console.error("取消收藏失败:", error);
          uni.showToast({
            title: "取消收藏失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 跳转到首页浏览
const goToBrowse = () => {
  uni.switchTab({
    url: "/pages/index/index",
  });
};
</script>

<style lang="scss" scoped>
.my-favorites-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.favorites-list {
  padding: 20rpx 30rpx;
}

.favorite-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  cursor: pointer;

  &:active {
    background-color: #f8f8f8;
  }
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-title {
  font-size: 30rpx;
  color: #333333;
  font-weight: 500;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  font-size: 32rpx;
  color: #ff4444;
  font-weight: bold;
  margin-bottom: 15rpx;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.seller-info {
  display: flex;
  align-items: center;
}

.seller-avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
}

.seller-name {
  font-size: 24rpx;
  color: #666666;
}

.favorite-time {
  font-size: 24rpx;
  color: #999999;
}

.goods-status {
  display: flex;
  align-items: center;
}

.favorite-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 15rpx;
  margin-left: 20rpx;
}

.contact-btn,
.unfavorite-btn {
  width: 120rpx;
  height: 60rpx;
  font-size: 24rpx;
  border-radius: 30rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.contact-btn {
  background-color: #07c160;
  color: #ffffff;
}

.unfavorite-btn {
  background-color: #ff4444;
  color: #ffffff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;
}

.empty-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 40rpx;
}

.browse-btn {
  width: 200rpx;
  height: 70rpx;
  background-color: #07c160;
  color: #ffffff;
  font-size: 28rpx;
  border-radius: 35rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
